<template>
  <div class="edit-class">
    <h1 class="page-title">编辑班级</h1>
    
    <div class="form-container" v-loading="loading">
      <el-form 
        :model="classForm" 
        :rules="rules" 
        ref="classFormRef" 
        label-width="100px"
        class="class-form"
      >
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="classForm.className" placeholder="请输入班级名称"></el-input>
        </el-form-item>
        <el-form-item label="班级编号" prop="classCode">
          <el-input v-model="classForm.classCode" placeholder="请输入班级编号"></el-input>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-select v-model="classForm.grade" placeholder="请选择年级">
            <el-option label="一年级" value="一年级"></el-option>
            <el-option label="二年级" value="二年级"></el-option>
            <el-option label="三年级" value="三年级"></el-option>
            <el-option label="四年级" value="四年级"></el-option>
            <el-option label="五年级" value="五年级"></el-option>
            <el-option label="六年级" value="六年级"></el-option>
            <el-option label="初一" value="初一"></el-option>
            <el-option label="初二" value="初二"></el-option>
            <el-option label="初三" value="初三"></el-option>
            <el-option label="高一" value="高一"></el-option>
            <el-option label="高二" value="高二"></el-option>
            <el-option label="高三" value="高三"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班主任" prop="headTeacherId">
          <el-select v-model="classForm.headTeacherId" placeholder="请选择班主任" filterable>
            <el-option
              v-for="item in teachersList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="classForm.createTime"
            type="date"
            placeholder="选择创建日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="classForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="classForm.remark" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入班级备注信息"
          ></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';

const router = useRouter();
const route = useRoute();
const classFormRef = ref(null);
const loading = ref(false);
const teachersList = ref([]);

// 获取班级ID
const classId = route.params.id;

// 表单数据
const classForm = reactive({
  id: '',
  className: '',
  classCode: '',
  grade: '',
  headTeacherId: '',
  createTime: '',
  status: 1,
  remark: ''
});

// 表单验证规则
const rules = {
  className: [
    { required: true, message: '请输入班级名称', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  classCode: [
    { required: true, message: '请输入班级编号', trigger: 'blur' }
  ],
  grade: [
    { required: true, message: '请选择年级', trigger: 'change' }
  ],
  headTeacherId: [
    { required: true, message: '请选择班主任', trigger: 'change' }
  ]
};

// 获取教师列表
const fetchTeachers = async () => {
  try {
    const response = await axios.get('/api/admin/teachers');
    if (response.data && response.data.success) {
      teachersList.value = response.data.data || [];
    } else {
      ElMessage.warning('获取教师列表失败');
    }
  } catch (error) {
    console.error('获取教师列表错误:', error);
    ElMessage.error('获取教师列表失败，请稍后重试');
  }
};

// 获取班级信息
const fetchClassInfo = async () => {
  loading.value = true;
  try {
    const response = await axios.get(`/api/admin/class/${classId}`);
    if (response.data && response.data.success) {
      const classData = response.data.data;
      Object.keys(classForm).forEach(key => {
        if (key in classData) {
          classForm[key] = classData[key];
        }
      });
    } else {
      ElMessage.error(response.data.message || '获取班级信息失败');
      goBack();
    }
  } catch (error) {
    console.error('获取班级信息错误:', error);
    ElMessage.error('获取班级信息失败，请稍后重试');
    goBack();
  } finally {
    loading.value = false;
  }
};

// 提交表单
const submitForm = async () => {
  if (!classFormRef.value) return;
  
  await classFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await axios.put(`/api/admin/class/${classForm.id}`, classForm);
        if (response.data && response.data.success) {
          ElMessage.success('更新班级信息成功');
          router.push('/admin/classes');
        } else {
          ElMessage.error(response.data.message || '更新班级信息失败');
        }
      } catch (error) {
        console.error('提交班级表单错误:', error);
        ElMessage.error(error.response?.data?.message || '操作失败，请稍后重试');
      }
    } else {
      return false;
    }
  });
};

// 重置表单
const resetForm = () => {
  fetchClassInfo();
};

// 返回
const goBack = () => {
  router.push('/admin/classes');
};

// 页面加载时获取数据
onMounted(async () => {
  if (classId) {
    await fetchTeachers();
    fetchClassInfo();
  } else {
    ElMessage.error('缺少班级ID参数');
    goBack();
  }
});
</script>

<style scoped>
.edit-class {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 24px;
  color: #333;
}

.form-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.class-form {
  max-width: 600px;
}
</style> 